<?php

class AdminUser extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model("admin_user_model", "user");
        $this->load->model("admin_role_model", "role");

        $this->load->service("admin_manage_service");
        $this->check = $this->admin_manage_service;
        $this->_adminInfo = $this->check->checkAdminLogin();
        #
        $this->projectUrl = [
            "add" => MANAGE_URL . "&c=adminUser&m=add",
            "list" => MANAGE_URL . "&c=adminUser&m=lists",
            "edit" => MANAGE_URL . "&c=adminUser&m=edit",
            "ajaxAdd" => MANAGE_URL . "&c=adminUser&m=ajaxAdd",
            "ajaxUpdate" => MANAGE_URL . "&c=adminUser&m=ajaxUpdate",
            "del" => MANAGE_URL . "&c=adminUser&m=del",
            "ajaxEditPassword" => MANAGE_URL . "&c=adminUser&m=ajaxEditPassword",
        ];
    }

    /*
     * 添加
     */

    function add() {

        try {

            #权限
            $this->check->checkPower(array("power" => "admin_user_add"));

            $data["navName"] = "添加";

            $data["status"] = $this->user->status();

            $adminRole = [];
            $role = $this->role->getData("where status_id=1", 1, 0);
            foreach ($role as $k => $v) {
                $adminRole[] = [
                    "id" => $v["id"],
                    "name" => $v["name"],
                ];
            }
            $data["adminRole"] = array_merge($adminRole, [$this->role->roleAdmin()]);
            
            //print_r($data["adminRole"]);

            $data["ajaxAddUrl"] = $this->projectUrl["ajaxAdd"];

            $this->layout->view('admin/adminUser/add', $data);
        } catch (Exception $e) {
            $msg = $e->getMessage();
            show_error($msg, 200, "系统提示");
        }
    }

    /*
     * 
     */

    function ajaxAdd() {


        $flag = 0;
        $msg = "操作失败";

        try {
            #权限
            $this->check->checkPower(array("power" => "admin_user_add"));

            $username = $this->input->postStr("username", true);
            $truename = $this->input->postStr("truename", true);
            $password = $this->input->postStr("password", true);
            $role_id = $this->input->postInt("role_id", true);
            $status_id = $this->input->postStr("status_id", true);
            $remark = $this->input->postStr("remark", true);

            if ($username == "") {
                throw new Exception("请填上用户名");
            }
            if (strlen($username) < 3) {
                throw new Exception("用户名至少3个字符");
            }
            if ($truename == "") {
                throw new Exception("请填上真实姓名");
            }

            $isUsernameExist = $this->user->isUsernameExist($username);
            if ($isUsernameExist) {
                throw new Exception("该用户名已存在");
            }
            if ($password == "") {
                throw new Exception("请填上密码");
            }
            if (strlen($password) < 6) {
                throw new Exception("设置的密码不能小于6个字符");
            }
            $password = $this->common->encryptPassword($password);

            //$password = $this->common->encryptPassword(substr($mobile, 5));

            $this->db->trans_start();

            $data = [
                "password" => $password,
                "truename" => $truename,
                "username" => $username,
                "remark" => $remark,
                "role_id" => $role_id,
                "status_id" => $status_id,
                'created_at' => time(),
                'updated_at' => time(),
            ];
            $insert_id = $this->user->addData($data);

            if ($insert_id) {
                $flag = 1;
                $msg = "操作成功";
            }
            $this->db->trans_complete();
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    /*
     * 编辑
     */

    function edit() {

        try {

            #权限
            $this->check->checkPower(array("power" => "admin_user_view"));

            $data["navName"] = "编辑";
            $data["status"] = $this->user->status();

            $id = $this->input->getInt("id", TRUE);

            $editData = $this->user->getDataById($id);
            if (empty($editData)) {
                throw new Exception("缺少用户id");
            }
            $data["editData"] = $editData;

            $adminRole = [];
            $role = $this->role->getData("where status_id=1", 1, 0);
            foreach ($role as $k => $v) {
                $adminRole[] = [
                    "id" => $v["id"],
                    "name" => $v["name"],
                ];
            }
            $data["adminRole"] = array_merge($adminRole, [$this->role->roleAdmin()]);

            $data["ajaxAddUrl"] = $this->projectUrl["ajaxUpdate"];

            $this->layout->view('admin/adminUser/add', $data);
        } catch (Exception $e) {
            $msg = $e->getMessage();
            show_error($msg, 200, "系统提示");
        }
    }

    /*
     * ajax编辑
     */

    function ajaxUpdate() {

        $flag = 0;
        $msg = "操作失败";

        try {
            #权限
            $this->check->checkPower(array("power" => "admin_user_edit"));

            $username = $this->input->postStr("username", true);
            $truename = $this->input->postStr("truename", true);
            $password = $this->input->postStr("password", true);
            $role_id = $this->input->postInt("role_id", true);
            $status_id = $this->input->postStr("status_id", true);
            $remark = $this->input->postStr("remark", true);

            $id = $this->input->postInt("id", TRUE);

            if ($id <= 0) {
                throw new Exception("缺少id参数");
            }
            $user = $this->user->getDataById($id);
            if (empty($user)) {
                throw new Exception("该账户不存在");
            }
            if ($username == "") {
                throw new Exception("请填上用户名");
            }
            if (strlen($username) < 3) {
                throw new Exception("用户名至少3个字符");
            }
            if ($truename == "") {
                throw new Exception("请填上真实姓名");
            }

            $isUsernameExist = $this->user->isUsernameExist($username, $id);
            if ($isUsernameExist) {
                throw new Exception("该用户名已存在");
            }

            $this->db->trans_start();

            $data = [
                "fieldArr" => [
                    "truename" => $truename,
                    "username" => $username,
                    "remark" => $remark,
                    "role_id" => $role_id,
                    "status_id" => $status_id,
                    'updated_at' => time(),
                ],
                "whereArr" => [
                    "id" => $id,
                ],
            ];
            if ($password != "") {
                if (strlen($password) < 6) {
                    throw new Exception("重设密码不可少于6位数");
                }
                $password = $this->common->encryptPassword($password);
                $data["fieldArr"]["password"] = $password;
            }
            $insert_id = $this->user->updateData($data);

            if ($insert_id) {
                $flag = 1;
                $msg = "操作成功";
            }

            $this->db->trans_complete();
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    /*
     * 删除记录
     */

    public function del() {

        $flag = 0;
        $msg = "操作失败";

        try {
            #权限
            $this->check->checkPower(array("power" => "admin_user_del"));

            $id = $this->input->postInt("id", TRUE);

            if ($id <= 0) {
                throw new Exception("参数错误");
            }
            $oldData = $this->user->getDataById($id);
            if (empty($oldData)) {
                throw new Exception("该账户不存在");
            }

            $this->db->trans_start();

            $paramArr = array(
                "whereArr" => array(
                    "id" => $id
                ),
            );
            $result = $this->user->delData($paramArr);
            if ($result) {

                $flag = 1;
                $msg = "操作成功";

                $this->db->trans_complete();
            }
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }
        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

    /*
     * 列表
     */

    function lists() {

        try {
            #权限
            $this->check->checkPower(array("power" => "admin_user_view"));

            $data["navName"] = "后台用户";

            $page = $this->input->getInt("page", TRUE);
            if ($page <= 0) {
                $page = 1;
            }
            $pageCount = 20;
            $data["page"] = $page;
            $data["pageCount"] = $pageCount;

            $pageStrArr = array();
            $where = "WHERE 1";

            //
            $keyword = $this->input->getPostStr("keyword", TRUE);
            if ($keyword != "") {
                $pageStrArr["keyword"] = $keyword;
                $where .= " AND username like '%" . $username . "%' and truename like '%" . $keyword . "%'";
            }
            $data["keyword"] = $keyword;

            $listNum = $this->user->getDataCount($where);

            $is_ajax = $this->input->is_ajax_request();

            if ($is_ajax) {
                $dataList = $this->user->getData($where, $page, $pageCount);

                $status = $this->user->status();

                $adminRole = [];
                $role = $this->role->getData("where status_id=1", 1, 0);
                foreach ($role as $k => $v) {
                    $adminRole[] = [
                        "id" => $v["id"],
                        "name" => $v["name"],
                    ];
                }
                $adminRole = array_merge($adminRole, [$this->role->roleAdmin()]);
                $adminRole = array_column($adminRole, null, "id");

                foreach ($dataList as $k => $v) {
                    $dataList[$k]["status_name"] = !empty($status[$v["status_id"]]["name"]) ? $status[$v["status_id"]]["name"] : "-";
                    $dataList[$k]["role_name"] = !empty($adminRole[$v["role_id"]]["name"]) ? $adminRole[$v["role_id"]]["name"] : "-";
                    $dataList[$k]["created_at_alias"] = date("Y-m-d H:i:s", $v["created_at"]);
                    $dataList[$k]["updated_at_alias"] = date("Y-m-d H:i:s", $v["updated_at"]);
                    $dataList[$k]["login_time_alias"] = $v["login_time"] > 0 ? date("Y-m-d H:i:s", $v["login_time"]) : "-";
                }
                $data["dataList"] = $dataList;

                $result = [
                    "code" => 0,
                    "count" => $listNum,
                    "data" => $dataList,
                    "msg" => ""
                ];
                echo jsonEncode($result);
                exit;
            }

            #进行分页
            $pageStr = "";
            if (!empty($pageStrArr)) {
                foreach ($pageStrArr as $k => $v) {
                    $pageStr .= "&" . $k . "=" . $v;
                }
            }
            $data['base_url'] = $this->projectUrl["list"] . $pageStr;

            $data["listNum"] = $listNum;

            $this->layout->view('admin/adminUser/list', $data);
        } catch (Exception $e) {
            $msg = $e->getMessage();
            show_error($msg, 200, "系统提示");
        }
    }

    function editPassword() {

        try {
            $data["navName"] = "修改密码";
            $this->layout->view('admin/adminUser/editPassword', $data);
        } catch (Exception $e) {
            $msg = $e->getMessage();
            show_error($msg, 200, "系统提示");
        }
    }

    function ajaxEditPassword() {


        $flag = false;
        $msg = "操作失败";
        try {

            $password_old = $this->input->postStr("password_old", TRUE);
            $password = $this->input->postStr("password", TRUE);
            $password_re = $this->input->postStr("password_re", TRUE);

            if ($password_old == "") {
                throw new Exception("请填上旧密码");
            }
            if ($password == "") {
                throw new Exception("请填上新密码");
            }
            if (strlen($password) < 6) {
                throw new Exception("新密码必须至少6个字符");
            }
            if ($password_re == "") {
                throw new Exception("请填上重复新密码");
            }
            if ($password != $password_re) {
                throw new Exception("新密码和重复新密码要相同");
            }

            $password_old = $this->common->encryptPassword($password_old);

            $password_data = $this->_adminInfo["password"];

            if ($password_old != $password_data) {
                throw new Exception("旧密码错误");
            }
            $password = $this->common->encryptPassword($password);

            $paramArr = array(
                "fieldArr" => array(
                    "password" => $password,
                ),
                "whereArr" => array(
                    "id" => $this->_adminInfo["id"],
                ),
            );
            $result = $this->user->updateData($paramArr);

            if ($result) {
                $flag = true;
                $msg = "操作成功";
            }
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }
        $outArr = array("flag" => $flag, "msg" => $msg);
        echo jsonEncode($outArr);
    }

}
